package com.leyou.item.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.GoodService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
public class GoodServiceImpl implements GoodService {

    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;


    @Override
    public PageResult<SpuBo> pageQuery(String key, Boolean saleable, Integer page, Integer rows) {

        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        PageHelper.startPage(page,rows);
        // 搜索条件
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        List<Spu> spus = this.goodMapper.selectByExample(example);

        List<SpuBo> spuBos = new ArrayList<>();
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        spus.forEach(spu -> {
            SpuBo bo=new SpuBo();
            BeanUtils.copyProperties(spu,bo);

            //查询分类名称:分类之间用“/”隔开
            List<String> names = this.categoryService.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            //设置品牌名称
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            if(brand==null){
                bo.setBname("");
            }else {
                bo.setBname(brand.getName());
            }
            bo.setCname(StringUtils.join(names,"/"));

            spuBos.add(bo);
        });

        return new PageResult<>(pageInfo.getTotal(),spuBos);
    }

    /*
      新增商品
     */
    @Transactional
    @Override
    public int saveGoods(SpuBo spuBo) {
        /*
        1.新增SPu
        2.新增spuDetail
        3.新增sku
        4. 新增stock
         */
        //  1
        spuBo.setId(null);
        //新增商品为上架商品
        spuBo.setSaleable(true);
        //是否有效，逻辑删除
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        this.spuMapper.insertSelective(spuBo);
        //  2
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapper.insertSelective(spuDetail);
        //  3
        saveSkuAndStock(spuBo);
        return 0;
    }

    private void saveSkuAndStock(SpuBo spuBo) {
        spuBo.getSkus().forEach(sku -> {
            sku.setId(null);
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());

            this.skuMapper.insertSelective(sku);
            //  4
            Stock stock=new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insertSelective(stock);
        });
    }

    @Override
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    @Override
    public List<Sku> querySkusById(Long spuId) {
        Sku sku=new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(sku);
        skus.forEach(s -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return skus;
    }

    @Transactional
    @Override
    public void updateGoods(SpuBo spuBo) {
        //根据spuId查询所有的sku
        Sku record=new Sku();
        record.setSpuId(spuBo.getId());
        List<Sku> skus = this.skuMapper.select(record);
        //根据skuId删除stock
        skus.forEach(sku -> {
            this.stockMapper.deleteByPrimaryKey(sku.getId());
        });
        //删除sku
        Sku sku=new Sku();
        sku.setSpuId(spuBo.getId());
        this.skuMapper.delete(sku);
        //新增sku
        //新增stock
        this.saveSkuAndStock(spuBo);//从新增模块模块抽取出来的方法
        //更新spu和spuDetail
        //创建时间不能该
        spuBo.setCreateTime(null);
        //更新时间应该是服务器时间
        spuBo.setLastUpdateTime(new Date());
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

    }
}
